package cn.portx;

import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.client.RestTemplate;

import com.bstek.ureport.console.UReportServlet;

import cn.portx.http.Bdf3LoginFilter;

@SpringBootApplication
@EnableCaching
@EnableScheduling
public class Application extends SpringBootServletInitializer {

	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
		builder.sources(Application.class);
		return super.configure(builder);
	}

	@Bean
	public ServletRegistrationBean getUReportServlet() {
		ServletRegistrationBean registration = new ServletRegistrationBean(new UReportServlet());
		registration.addUrlMappings("/ureport/*");
		return registration;
	}

	@Bean
	public FilterRegistrationBean bdf3LoginFilter() {
		FilterRegistrationBean registration = new FilterRegistrationBean(new Bdf3LoginFilter());
		registration.addUrlPatterns("/bdf3.saas.ui.view.Login.d");
		return registration;
	}

	@Bean
	@Primary
	public PasswordEncoder getM5PasswordEncoder() {

		return new PasswordEncoder() {
			@Override
			public String encode(CharSequence rawPassword) {
				String encodedPassword = DigestUtils.md5Hex(rawPassword.toString()).toUpperCase();
				return encodedPassword;
			}

			@Override
			public boolean matches(CharSequence rawPassword, String encodedPassword) {
				String shouldEncodedPassword = DigestUtils.md5Hex(rawPassword.toString()).toUpperCase();
				return StringUtils.equals(shouldEncodedPassword, encodedPassword);
			}

		};
	}

	@Bean
	public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
		return new RestTemplate(factory);
	}

	@Bean
	public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
		SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
		return factory;
	}

	public static void main(String[] args) throws Exception {
		SpringApplication.run(Application.class, args);
	}

}
